package com.example.dao;

import com.example.entity.User;
import java.sql.*;

public class UserDaoImpl implements UserDao {

    private final Connection connection;

    public UserDaoImpl() throws SQLException {
        try {
            this.connection = getConnection(); // 自动从 Dao 获取连接
        } catch (SQLException e) {
            throw new RuntimeException("数据库连接失败", e);
        }
    }

    @Override
    public boolean isUsernameExists(String username) throws SQLException {
        String sql = "SELECT COUNT(*) FROM user WHERE username = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, username);
            try (ResultSet rs = stmt.executeQuery()) {
                return rs.next() && rs.getInt(1) > 0;
            }
        }
    }

    @Override
    public boolean registerUser(User user) throws SQLException {
        String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        }
    }
}

